import { BrowserWindow, app, shell } from 'electron';
import icon from '../../resources/icon.png?asset'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'

let fiveWin = null;

const createfiveWin = () => {
    fiveWin = new BrowserWindow({
        title: 'Yangshao 五子棋',
        width: 400,
        height: 480,
        autoHideMenuBar: true,
        icon: icon,
        webPreferences: {
            nodeIntegration: true,
            preload: join(__dirname, '../preload/index.js'),
        },
        resizable: false,
        show:false

    });
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
        fiveWin.loadURL(process.env['ELECTRON_RENDERER_URL'])
    } else {
        fiveWin.loadFile(join(__dirname, '../renderer/index.html'))
    }
    // 假设你想在创建窗口后立即打开设置路由
    fiveWin.webContents.on('did-finish-load', () => {
        fiveWin.webContents.send('set-route', '/five');
    });

    fiveWin.webContents.setWindowOpenHandler((details) => {
        if (url.startsWith('https:')) shell.openExternal(url);
        return { action: 'deny' }
    })

    return fiveWin;
}
function closefiveWin() {
    if (fiveWin && !fiveWin?.isDestroyed()) {
        fiveWin?.close();
    }
    fiveWin = null;
}

function openfiveWin() {
    if (!fiveWin || fiveWin?.isDestroyed()) {
        fiveWin = createfiveWin();
    }
}
function showfiveWin(){
    fiveWin?.show();
}
function hidefiveWin() {
    fiveWin.hide();
}
// 写一个show和hide切换
function showHidefiveWin() {
    fiveWin.isVisible() ? fiveWin.hide() : fiveWin.show();
}
function goHomefiveWin() {
    fiveWin.loadURL('http://localhost:3456/five')
}

function minimizefiveWin() {
    fiveWin.minimize();
}

function focusfiveWin() {
    if (!fiveWin || fiveWin?.isDestroyed()) {
        fiveWin = createfiveWin();
    } else {
        // Focus on the main window if the user tried to open another
        if (fiveWin.isMinimized()) fiveWin.restore();
        if (!fiveWin.isVisible()) fiveWin.show();
        fiveWin.focus();
    }
}

function sendEuUpdateCanAvailable(arg, update) {
    if (fiveWin && !fiveWin?.isDestroyed()) {
        fiveWin.webContents.send('eu:update-can-available', {
            update: update,
            version: app.getVersion(),
            newVersion: arg?.version,
        });
    }
}

export {
    closefiveWin,
    createfiveWin,
    showfiveWin,
    focusfiveWin,
    hidefiveWin,
    minimizefiveWin,
    openfiveWin,
    sendEuUpdateCanAvailable,
    showHidefiveWin,
    goHomefiveWin
};